<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>KingDrive</title>
</head>
<link rel="stylesheet" href="/res/layui/css/layui.css" media="all">
<script type='text/javascript' src='../res/jquery-3.5.1.js'></script>
<script type="text/javascript" src="Popup.js"></script>
<script src="../res/layui/layui.js"></script>
<!--<link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet">-->
<!--&lt;!&ndash; 最新的 Bootstrap 核心 JavaScript 文件 &ndash;&gt;-->
<!--<script src="../bootstrap/js/bootstrap.min.js"></script>-->
<script src="../res/axios.js"></script>
<script type="text/javascript" src="/res/vue.js"></script>
<script>
    //JS
    let tableS; //表格模块
    let layerS; //弹出层
    let uploadS;//文件上传模块
    let elementS;
    layui.use(['code', 'table', 'element', 'layer', 'util', 'upload'], function () {
        const element = layui.element
            , layer = layui.layer
            , util = layui.util
            , $ = layui.$;
        layerS = layui.layer;
        tableS = layui.table;
        uploadS = layui.upload;
        elementS = layui.element;
        //头部事件
        util.event('lay-header-event', {
            //左侧菜单事件
            menuLeft: function (othis) {
                layer.msg('展开左侧菜单的操作', {icon: 0});
            }
            , menuRight: function () {
                layer.open({
                    type: 1
                    , content: '<div style="padding: 15px;">处理右侧面板的操作</div>'
                    , area: ['260px', '100%']
                    , offset: 'rt' //右上角
                    , anim: 5
                    , shadeClose: true
                });
            }
        });

    });

    /**
     * 文件下载
     * @param isFile
     * @param filePath
     */
    function download(isFile, filePath) {
        if (isFile) {
            let elemIf = document.createElement("iframe")
            elemIf.src = "/downFile?path=" + filePath;
            elemIf.style.display = "none";
            document.body.appendChild(elemIf);
        } else {
            let elemIf = document.createElement("iframe")
            elemIf.src = "/downDir?path=" + filePath;
            elemIf.style.display = "none";
            document.body.appendChild(elemIf);
        }


    }
</script>
<body onload="queryFile()">

<div class="layui-layout layui-layout-admin" id="main">
    <div class="layui-header layui-bg-cyan" id="head">
        <div class="layui-logo layui-hide-xs layui-bg-blue">KingDrive</div>
        <!-- 头部区域（可配合layui 已有的水平导航） -->
        <ul class="layui-nav layui-layout-left layui-bg-cyan">
            <!-- 移动端显示 -->
            <li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm"
                lay-header-event="menuLeft">
                <i class="layui-icon layui-icon-spread-left"></i>
            </li>
            <img style="width: 30px" src="/res/svg/分隔.svg" alt="">
            <li class="layui-nav-item">
                新建<img style="width: 30px" src="/res/svg/新建.svg" alt="">
                <dl class="layui-nav-child">
                    <dd><a @click="newFile">新建文件</a></dd>
                    <dd><a @click="newDir">新建文件夹</a></dd>
                </dl>
            </li>
            <img style="width: 30px" src="/res/svg/分隔.svg" alt="">
            <li class="layui-nav-item layui-hide-xs">
                上传
                <img style="width: 30px" src="/res/svg/上传.svg" alt="">
                <dl class="layui-nav-child">
                    <dd>

                    </dd>
                    <dd>
                        <input type="file" class="layui-btn" name="upload-file" id="upload-file" @change="uploadFile">
                    </dd>
                </dl>
            </li>
            <li class="layui-nav-item layui-hide-xs"><a href="">回收站</a></li>

        </ul>
        <ul class="layui-nav layui-layout-right">
            <li class="layui-nav-item layui-hide layui-show-md-inline-block">

                <img src="//tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg"
                     class="layui-nav-img">
                {{user.name}}
                </a>
                <dl class="layui-nav-child">
                    <dd><a href="">个人中心</a></dd>
                    <dd><a href="">设置</a></dd>
                    <dd><a href="">····</a></dd>
                    <dd><a href="">退出登录</a></dd>
                </dl>
            </li>
            <li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
                <a href="javascript:;">
                    <i class="layui-icon layui-icon-more-vertical"></i>
                </a>
            </li>
        </ul>
    </div>

    <div class="layui-side layui-bg-cyan">
        <div class="layui-side-scroll ">
            <!-- 左侧导航区域（可配合layui已有的垂直导航） -->
            <ul class="layui-nav layui-nav-tree " lay-filter="test">
                <li class="layui-nav-item layui-nav-itemed">
                    <a class="" href="index.html">全部文件</a>
                    <dl class="layui-nav-child">
                        <dd><a href="file.html#1">图片</a></dd>
                        <dd><a href="file.html#2">文档</a></dd>
                        <dd><a href="file.html#3">视频</a></dd>
                        <dd><a href="file.html#">种子</a></dd>
                        <dd><a href="file.html#4">音乐</a></dd>
                        <dd><a href="file.html#5">其他</a></dd>
                    </dl>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;">我的分享</a>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;">回收站</a></li>
            </ul>
        </div>
    </div>

    <div id="bodyS" class="layui-body layui-bg-gray">
        <!-- 内容主体区域 -->

        <div style="padding: 15px;width: 100%" class="layui-inline">

            <div class="layui-input-inline" style="width: 800px;">
                <input v-model="path" type="text" id="path" class="layui-input">
            </div>

            <div class="layui-input-inline" style="width: 100px;">
                <button id="GO" type="button" class="layui-btn  layui-border-blue" @click="gotoPath">GO</button>
            </div>


        </div>
        <div style="width: 100%" id="fileTable">

            <table id="singers" lay-data="{initSort : {field:'size', type:'asc'}}" lay-filter="demo"
                   style="height: 40%">
                <thead>
                <tr>
                    <th lay-data="{field:'fileName', width:300}">文件名</th>
                    <th lay-data="{field:'size', width:100, sort:true}">大小</th>
                    <th lay-data="{field:'date' , sort:true}">修改日期</th>
                    <th lay-data="{fixed: 'right',title:'操作',  width:300, align:'center', toolbar: '#barDemo'}"></th>
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
        <div class="layui-footer">
            <!-- 底部固定区域 -->
            <img style="width: 20px" src="/res/svg/文件夹.svg">
            底部固定区域
        </div>
    </div>
</div>

<script type="text/javascript">
    function gotoPre() {
        king.gotoPrev();
    }

    function FgetPath() {
        window.setTimeout(function () {
            console.log("你好啊！！！");
            location.reload();
            queryFile()
        }, 300);
    }

    function queryFile() {
        const path = king.getPath();
        let files = [];
        axios.post('/getFile?path=' + path).then(res => {
            if (res.data.code === 1) {
                files = res.data.obj;
                //console.log(files)
                //$("#singers  tr:not(:first)").nextAll().remove();
                const $table = $("#singers");
                //文件大小
                let filesize = "";
                let isDir = "";

                for (const i of files) {
                    //console.log(i.path)
                    // var dirPath = i.path;
                    if (i.is === false) {
                        console.log("路径错误")
                    }
                    if (i.isDirectory === true) {
                        filesize = " ";
                        isDir = "<img style='height: 20px;width: 20px'  src='../res/svg/文件夹.png'>"
                        i.name = "<a  name='name' onclick='FgetPath()' value='name' href='#" + i.path + "'>" + i.name + "</a>"
                    } else {
                        filesize = i.fileSize + " kb";
                        isDir = "<img style='height: 20px;width: 20px' src='../res/svg/文件.png' alt='#" + i.path + "'>"
                    }

                    $table.append("<tr>" +

                        "<td>" + isDir + "&nbsp;&nbsp;&nbsp;&nbsp;" + i.name + "</td>" +
                        "<td>" + filesize + "</td>" +
                        "<td>" + i.modification_time + "</td>" +
                        "</tr>");

                    // var table = layui.table;

                    //转换静态表格
                    tableS.init('demo', {
                        height: 600 //设置高度
                        , limit: files.length //注意：请务必确保 limit 参数（默认：10）是与你服务端限定的数据条数一致
                        , page: true //开启分页
                        , toolbar: '#toolbarDemo'
                        //, curr: 10 //设定初始在第 12 页
                        //支持所有基础参数
                    });
                    //工具条事件
                    tableS.on('tool(demo)', function (obj) {
                        //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                        var data = obj.data;
                        //获得当前行数据
                        var layEvent = obj.event;
                        //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                        var tr = obj.tr;
                        //获得当前行 tr 的 DOM 对象（如果有的话）

                        console.log(layEvent)
                        var path = data.fileName;
                        console.log(path)
                        var isFile;
                        if (path.indexOf("文件.png") >= 0) {
                            isFile = true;
                        } else {
                            isFile = false;
                        }
                        console.log(isFile)
                        //选中的文件路径 如果是文件附带文件名
                        path = path.substring(path.lastIndexOf("#") + 1, path.lastIndexOf('"'))
                        var name = path.substring(path.lastIndexOf("/"), path.length);
                        console.log(path + name)


                        let data1;
                        if (layEvent === 'detail') { //查看
//查看操作
                            //判断是否为图片
                            let patty = new RegExp(".+(.jpeg|.jpg|.png|.bmp|.gif|.JPG)$");
                            if (patty.test(name)) {
                                //弹窗 显示图片
                                // //页面层-图片
                                layer.open({
                                    type: 1,
                                    title: name,
                                    closeBtn: 0,
                                    area: ['900px', '506px'],
                                    skin: 'layui-layer-nobg', //没有背景色
                                    shadeClose: true,
                                    content:
                                        "<div class='div1'>" +
                                        "<img  src='/lookPhoto?path=" + path + "' alt=''>" +
                                        "<a class='layui-btn layui-btn-normal' href='/lookPhoto?path=" + path + "'>查看原图</a>" +
                                        "</div>"
                                });

                            } else if (new RegExp(".+(.txt|.html|.hml|.js|.cpp|.css)$").test(name)) {
                                var txt;
                                axios.post("/lookDoc?path=" + path).then(res => {
                                    txt = res.data.data;
                                    //弹窗 显示文字
                                    layer.open({
                                        type: 1,
                                        title: name,
                                        shade: false,
                                        area: ['900px', '506px'],
                                        maxmin: true,
                                        content: '<pre class="layui-code" style="height: 100%">\n' +
                                            txt +
                                            '</pre>',
                                        zIndex: layer.zIndex, //重点1
                                    });

                                });
                                layui.code({
                                    encode: true //是否转义html标签。默认不开启
                                });
                            } else {
                                layer.msg('抱歉当前文件不支持预览', {icon: 6});
                            }

                            //do somehing
                        } else if (layEvent === 'del') { //删除
                            layer.confirm('真的删除这个文件吗', function (index) {
                                obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                                layer.close(index);
                                axios.post('/delFile?path=' + path).then(res => {
                                    data1 = res.data;
                                    layerS.msg(data1.msg);
                                });
                                //向服务端发送删除指令
                            });
                        } else if (layEvent === 'edit') { //编辑
                            //do something
                            var oldName = path.substring(path.lastIndexOf("/") + 1, path.length);
                            path = path.substring(0, path.lastIndexOf("/"));
                            console.log("oldName " + oldName + "  path " + path);
                            let data;
                            layerS.prompt({
                                formType: 0,
                                value: '',//初始值
                                title: '请输入新的文件名'
                            }, function (value, index, elem) {
                                //alert(value); //得到value
                                let params = new URLSearchParams();
                                params.append('path', path);
                                params.append('oldName', oldName);
                                params.append('newName', value);

                                axios.post("/changeFileName", params).then(res => {
                                    if (res.data.code === 0) {
                                        layerS.msg(res.data.msg)
                                    } else {
                                        layerS.msg(res.data.msg, {icon: 1});
                                    }
                                });
                                layerS.close(index);
                            });
                            // //同步更新缓存对应的值
                            // obj.update({
                            //     username: '123'
                            //     , title: 'xxx'
                            // });
                        } else if (layEvent === 'down') {
                            console.log("layEvent down")
                            download(isFile,path)
                        }
                    });
                    //
                    // //触发行单击事件
                    // tableS.on('row(demo)', function (obj) {
                    //     console.log(obj.tr) //得到当前行元素对象
                    //     console.log(obj.data) //得到当前行数据
                    //
                    //     //obj.del(); //删除当前行
                    //     //obj.update(fields) //修改当前行数据
                    // });
                    //触发行双击事件
                    tableS.on('rowDouble(demo)', function (obj) {
                        console.log(obj.tr) //得到当前行元素对象
                        console.log(obj.data) //得到当前行数据
                        //
                        //     obj.del(); //删除当前行
                        //     obj.update(fields) //修改当前行数据
                    });
                }
            }
        });


    }
</script>
<script type="text/javascript">
    const king = new Vue({
        el: '#main',
        data: {
            user: {}, //用户信息
            path: '/', //路径信息
        },
        mounted: function () {

            axios.post('/getUser').then(res => {
                console.log(res.data.code)
                if (res.data.code === 0) {
                    gotoLogin(res.data.msg, "/index.html");
                } else {
                    this.user = res.data.obj;
                }
            });

        },
        methods: {
            //获取网页链接http://localhost:8080/user/index.html#/文件夹1/文件夹4/css/res/
            //#号后面的数据 就是访问文件的路径
            getPath: function () {
                let test = window.location.hash;
                test = decodeURI(test);
                test = test.substring(1, test.length);
                this.path = test;
                console.log(this.path)
                return this.path;
            },
            gotoPath: function () {
                window.location.href = "/user/index.html#" + this.path;
                location.reload();
            },
            //去指定路径
            gotoPath2: function (goPath) {
                this.path = goPath;
                window.location.href = "/user/index.html#" + this.path;
                location.reload();
            },
            //返回上上一级
            gotoPrev: function () {
                var p = this.path;
                p = p.substring(0, p.lastIndexOf("/"))
                console.log(p)
                this.gotoPath2(p);
            },
            newFile: function () {

            },
            //新建一个文件夹
            newDir: function () {
                this.pop1()
            },
            pop1: function () {
                const that = this;
                layerS.prompt({
                    formType: 0,
                    value: '',//初始值
                    title: '请输入新建的文件名'
                }, function (value, index, elem) {
                    //alert(value); //得到value
                    axios.post('/newDir?dirPath=' + that.path + "/" + value).then(res => {
                        if (res.data.code === 0) {
                            layerS.msg(res.data.msg)
                        } else {
                            layerS.msg(res.data.msg, {icon: 1});
                        }
                        location.reload();
                    });
                    layerS.close(index);
                });
            },
            //修改文件名
            changeName: function () {

            },
            //文件上传
            uploadFile: function (e) {
                var file = e.target.files[0];
                var formdata = new FormData()
                formdata.append("file", file)
                formdata.append("uploadPath", this.path)
                console.log("文件", formdata);
                axios.post(
                    '/file/upload',
                    formdata,
                    {headers: {'Content-Type': 'multipart/form-data'}}
                ).then(function (res) {
                    if (res.data.code === 0) {
                        layerS.msg(res.data.msg)
                    } else {
                        layerS.msg(res.data.msg, {icon: 1});
                    }
                })
            },

        }

    });

</script>
</body>
<!--表格工具-->
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-radius layui-btn-sm layui-btn-normal" onclick="gotoPre()">
            <i class="layui-icon layui-icon-prev"></i>
            返回上一级
        </button>
    </div>
</script>
<script type="text/html" id="barDemo">
    <a title="查看" class="layui-btn layui-btn-xs" lay-event="detail">查看</a>
    <button title="重命名" class="layui-btn layui-btn-xs" lay-event="edit">&nbsp;
        <i class="layui-icon layui-icon-edit"></i>&nbsp;
    </button>
    <button title="删除" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">&nbsp;
        <i class="layui-icon layui-icon-delete"></i>&nbsp;
    </button>
    <button title="下载" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="down">&nbsp;
        <i class="layui-icon layui-icon-download-circle"></i>&nbsp;
    </button>
</script>
</html>